import "./index.less";
import React, { useState, useCallback } from "react";
import { Alert, Upload, Button as AButton, Modal, message } from "antd";
import type { UploadProps, UploadChangeParam, RcFile } from "antd/lib/upload/interface";
import type { ColumnsType } from "antd/es/table";
import { useUploadType } from "../useUpload";
import { buildUUID } from "@/utils/uuid";
import { useTranslation } from "react-i18next";
import FileList from "../FileList/index"; // 假设你有一个等效的 React 组件
import { checkImgType, getBase64WithFile } from "../helper";
import { UploadResultStatus } from "../typing";
import { createActionColumn, createTableColumns } from "../data/index";
interface FileItem {
	uuid: string;
	file: RcFile;
	size: number;
	name: string;
	percent: number;
	type?: string;
	thumbUrl?: string;
	status: UploadResultStatus;
	responseData?: any;
}

interface Props {
	api?: (params: any) => Promise<any>;
	uploadParams?: any;
	name?: string;
	filename?: string;
	previewFileList?: string[];
	helpText?: string;
	accept?: string;
	maxNumber?: number;
	maxSize?: number;
	multiple?: boolean;
	onChange?: (fileList: string[]) => void;
	onDelete?: (record: FileItem) => void;
}

const BasicUploadModal: React.FC<Props> = ({
	api,
	uploadParams,
	name,
	filename,
	previewFileList = [],
	helpText,
	accept,
	maxNumber = Infinity,
	maxSize,
	multiple = true,
	onChange,
	onDelete
}) => {
	const [isUploading, setIsUploading] = useState(false);
	const [fileList, setFileList] = useState<FileItem[]>([]);
	const [visible, setVisible] = useState(false);
	const { t } = useTranslation();
	const { getStringAccept, getHelpText } = useUploadType({ accept, helpText, maxNumber, maxSize });

	const columns = createTableColumns() as ColumnsType<FileItem>;
	const actionColumn = createActionColumn(onDelete);

	const getIsSelectFile = fileList.length > 0 && !fileList.every(item => item.status === UploadResultStatus.SUCCESS);
	const getOkButtonProps = {
		disabled: isUploading || fileList.length === 0 || !fileList.some(item => item.status === UploadResultStatus.SUCCESS)
	};
	const getUploadBtnText = isUploading
		? t("component.upload.uploading")
		: fileList.some(item => item.status === UploadResultStatus.ERROR)
		? t("component.upload.reUploadFailed")
		: t("component.upload.startUpload");

	const beforeUpload: UploadProps["beforeUpload"] = async file => {
		if (maxSize && file.size / 1024 / 1024 >= maxSize) {
			message.error(t("component.upload.maxSizeMultiple", [maxSize]));
			return false;
		}

		const commonItem = {
			uuid: buildUUID(),
			file,
			size: file.size,
			name: file.name,
			percent: 0,
			type: file.name.split(".").pop()
		};

		if (checkImgType(file)) {
			const { result: thumbUrl } = await getBase64WithFile(file);
			setFileList(prev => [...prev, { ...commonItem, thumbUrl }]);
		} else {
			setFileList(prev => [...prev, commonItem]);
		}
		return false; // 阻止默认上传行为
	};

	// const handleRemove = useCallback(
	// 	(record: FileItem) => {
	// 		setFileList(prev => prev.filter(item => item.uuid !== record.uuid));
	// 		onDelete?.(record);
	// 	},
	// 	[onDelete]
	// );

	const uploadApiByItem = useCallback(
		async (item: FileItem) => {
			try {
				item.status = UploadResultStatus.UPLOADING;
				const response = await api(
					{
						data: { ...(uploadParams || {}) },
						file: item.file,
						name,
						filename
					},
					(progressEvent: ProgressEvent) => {
						const complete = ((progressEvent.loaded / progressEvent.total) * 100) | 0;
						item.percent = complete;
					}
				);
				item.status = UploadResultStatus.SUCCESS;
				item.responseData = response.data;
				return { success: true, error: null };
			} catch (e) {
				console.log(e);
				item.status = UploadResultStatus.ERROR;
				return { success: false, error: e };
			}
		},
		[api, uploadParams, name, filename]
	);

	const handleStartUpload = useCallback(async () => {
		if (fileList.length + previewFileList.length > maxNumber) {
			message.warning(t("component.upload.maxNumber", [maxNumber]));
			return;
		}

		try {
			setIsUploading(true);
			const uploadFileList = fileList.filter(item => item.status !== UploadResultStatus.SUCCESS);
			const results = await Promise.all(uploadFileList.map(uploadApiByItem));

			const errorList = results.filter(result => !result.success);
			if (errorList.length > 0) throw errorList;

			setIsUploading(false);
		} catch (e) {
			setIsUploading(false);
			throw e;
		}
	}, [fileList, previewFileList, maxNumber, uploadApiByItem, t]);

	const handleOk = useCallback(() => {
		if (fileList.length > maxNumber) {
			message.warning(t("component.upload.maxNumber", [maxNumber]));
			return;
		}

		if (isUploading) {
			message.warning(t("component.upload.saveWarn"));
			return;
		}

		const uploadedUrls = fileList
			.filter(item => item.status === UploadResultStatus.SUCCESS && item.responseData)
			.map(item => item.responseData.url);

		if (uploadedUrls.length <= 0) {
			message.warning(t("component.upload.saveError"));
			return;
		}

		setFileList([]);
		setVisible(false);
		onChange?.(uploadedUrls);
	}, [fileList, maxNumber, isUploading, onChange, t]);

	// const handleCloseFunc = useCallback(() => {
	// 	if (!isUploading) {
	// 		setFileList([]);
	// 		return true;
	// 	} else {
	// 		message.warning(t("component.upload.uploadWait"));
	// 		return false;
	// 	}
	// }, [isUploading, t]);

	return (
		<Modal
			title={t("component.upload.upload")}
			visible={visible}
			okText={t("component.upload.save")}
			onOk={handleOk}
			onCancel={() => setVisible(false)}
			closeIcon={<span />}
			closable={false}
			maskClosable={false}
			keyboard={false}
			className="upload-modal"
			okButtonProps={getOkButtonProps}
			cancelButtonProps={{ disabled: isUploading }}
			destroyOnClose
		>
			<div className="upload-modal-toolbar">
				<Alert message={getHelpText} type="info" banner className="upload-modal-toolbar__text" />
				<Upload
					accept={getStringAccept}
					multiple={multiple}
					beforeUpload={beforeUpload}
					showUploadList={false}
					className="upload-modal-toolbar__btn"
					onChange={(info: UploadChangeParam) => {
						console.log(info);
					}}
				>
					<AButton type="primary">{t("component.upload.choose")}</AButton>
				</Upload>
			</div>
			<FileList dataSource={fileList} columns={columns} actionColumn={actionColumn} />
			<div className="upload-modal-footer">
				<AButton color="success" disabled={!getIsSelectFile} loading={isUploading} onClick={handleStartUpload}>
					{getUploadBtnText}
				</AButton>
			</div>
		</Modal>
	);
};

export default BasicUploadModal;
